package main

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"strings"
)

func makeOption() *fyne.Container {
	radio := widget.NewRadioGroup([]string{"rm -I", "rm -rf"}, func(value string) {
		commandWay = value
	})
	hbox := container.NewHBox(
		widget.NewLabel("删除方式："),
		radio,
	)
	return hbox
}

func makeReplOption() *fyne.Container {
	query := NewQuery()
	htmlStr, dodStr := query.GetConfig()
	radio := widget.NewRadioGroup([]string{"doc", "html"}, func(value string) {
		if value == "doc" {
			replaceStr = htmlStr
		}
		if value == "html" {
			replaceStr = dodStr
		}
		//replaceStr = value
	})
	hbox := container.NewHBox(
		widget.NewLabel("替换前缀："),
		radio,
	)
	return hbox
}

func manualWay(myWindow fyne.Window) *fyne.Container {
	opt := makeOption()
	repOpt := makeReplOption()

	submitBtn := widget.NewButtonWithIcon("生成代码", theme.FileApplicationIcon(), func() {
		prefix := commandWay + "  "
		for _, entry := range entries {
			if entry.Text != "" {
				// 去除文本中的换行符，包括 \r、\n 和 \r\n
				text := strings.NewReplacer("\r\n", "", "\r", "", "\n", "").Replace(entry.Text)
				prefix += shouldReplace(text) + " "
			}
		}
		dialog.ShowConfirm("确认", "复制代码吗?", func(confirmed bool) {
			if confirmed {
				myWindow.Clipboard().SetContent(prefix)
				dialog.ShowInformation("已复制到剪贴板", prefix, myWindow)
				prefix = ""
			} else {
				dialog.ShowInformation("放弃", "已取消复制", myWindow)
			}
		}, myWindow)
	})

	submitBtn.Importance = widget.HighImportance
	submitBtn.Refresh()

	form = widget.NewForm()
	addBtn := widget.NewButtonWithIcon("添加项", theme.DocumentCreateIcon(), func() {
		updateForm()
	})
	addBtn.Importance = widget.WarningImportance
	addBtn.Refresh()
	clearBtn := widget.NewButtonWithIcon("清空", theme.ContentClearIcon(), func() {
		clearForm()
	})
	clearBtn.Importance = widget.DangerImportance
	clearBtn.Refresh()

	formContainer := container.New(layout.NewVBoxLayout(), form)
	buttonContainer := container.New(layout.NewHBoxLayout(), addBtn, submitBtn, clearBtn)
	centerContainer := container.New(layout.NewCenterLayout(), buttonContainer)
	c = container.New(layout.NewVBoxLayout(), opt, repOpt, formContainer, centerContainer)
	return c
}

func AddItem() *widget.FormItem {
	totalItem++
	itemEntry := widget.NewEntry()
	formItem := widget.NewFormItem(fmt.Sprintf("项目%d", totalItem), itemEntry)
	entries = append(entries, itemEntry)
	return formItem
}

func updateForm() {
	newFormItem := AddItem()
	form.AppendItem(newFormItem)
	form.Refresh()
}

func clearForm() {
	entries = []*widget.Entry{}
	form.Items = []*widget.FormItem{}
	totalItem = 0
	form.Refresh()
}
